package com.haidechizi.fastadmin.common.base;

import com.haidechizi.fastadmin.common.utils.DateUtils;
import com.haidechizi.fastadmin.common.utils.StringUtils;
import com.haidechizi.fastadmin.modules.sys.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * Controller公共组件
 */
public abstract class AbstractController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected SysUser getUser() {
        return (SysUser) SecurityUtils.getSubject().getPrincipal();
    }

    protected Long getUserId() {
        return getUser().getUserId();
    }

    protected Long getOfficeId() {
        return getUser().getOfficeId();
    }

    /**
     * 参数类型转换
     *
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new MyDateEditor());
        /*
            从PropertyEditorSupport 实现的方法可以看出，这里的绑定是为了处理空和null的数据，
            开发者可根据实际情况绑定
        */
        binder.registerCustomEditor(Double.class, new DoubleEditor());
        binder.registerCustomEditor(Integer.class, new IntegerEditor());
    }

    private class MyDateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            Date date = DateUtils.parseDate(text);
            setValue(date);
        }
    }

    public class DoubleEditor extends PropertiesEditor {
        @Override
        public String getAsText() {
            return getValue().toString();
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            Double value = null;
            if (StringUtils.isNotBlank(text)) {
                value = Double.parseDouble(text);
            }
            setValue(value);
        }
    }

    public class IntegerEditor extends PropertiesEditor {
        @Override
        public String getAsText() {
            return getValue().toString();
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            Integer value = null;
            if (StringUtils.isNotBlank(text)) {
                value = Integer.parseInt(text);
            }
            setValue(value);
        }
    }
}
